package com.example.administrator.zhjt.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.example.administrator.zhjt.LoadingDialog;
import com.example.administrator.zhjt.MyService;
import com.example.administrator.zhjt.R;
import com.example.administrator.zhjt.bean.Event;
import com.example.administrator.zhjt.bean.Station;
import com.example.administrator.zhjt.util.MyVolley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class BusActivity extends AppCompatActivity implements View.OnClickListener {

    private static boolean isExit=false;
    private TextView tvPlatfromoneDistanceOne;
    private TextView tvPlatfromoneTimeone;
    private TextView tvPlatfromoneDistanceTwo;
    private TextView tvPlatfromoneTimetwo;
    private TextView tvPlatfromtwoDistanceOne;
    private TextView tvPlatfromtwoTimeone;
    private TextView tvPlatfromtwoDistanceTwo;
    private TextView tvPlatfromtwoTimetwo;
    private Button bt_quiry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bus);
        initView();
        MyVolley.init(this);
        EventBus.getDefault().register(this);

        Intent intent = new Intent(this, MyService.class);
        startService(intent);
        showloadingDialog();
    }

    AlertDialog alertDialog;
    int second = 0 ;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event){
        if(event != null){
            switch (event.getType()){
                case CYCLE:
                    second++;
                    if(second % 5 == 0){
                        System.out.println("i");
                    }

                    break;
                case NO_NETWORK:
                    if(!alertDialog.isShowing()){
                        alertDialog.show();
                    }
                    break;
            }

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void Post() {

        MyVolley.getBusStationinfo(1, new MyVolley.OnResultListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    String array = result.getString("ROWS_DETAIL").replace("\\n", "").replace("\\", "");
                    List<Station> stations = new Gson().fromJson(array, new TypeToken<List<Station>>() {
                    }.getType());
                    System.out.println(result);
                    for (Station station : stations) {
                        if (station.getBusId() == 1) {
                            tvPlatfromoneDistanceOne.setText("距离"+station.getDistance());
                            tvPlatfromoneTimeone.setText("剩余时间"+station.getDistance()/20000+"分钟");
                        }
                        if (station.getBusId()==2){
                            tvPlatfromoneDistanceTwo.setText("距离"+station.getDistance());
                            tvPlatfromoneTimetwo.setText("剩余时间"+station.getDistance()/20000+"分钟");
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {
                error.printStackTrace();
            }
        });

        MyVolley.getBusStationinfo(2, new MyVolley.OnResultListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    String array=result.getString("ROWS_DETAIL").replace("\\n","").replace("\\","");
                    List<Station> stations=new Gson().fromJson(array,new TypeToken<List<Station>>(){}.getType());
                    for (Station station:stations){
                        if (station.getBusId()==1){
                            tvPlatfromtwoDistanceOne.setText("距离"+station.getDistance()+"m");
                            tvPlatfromtwoTimeone.setText("剩余时间"+station.getDistance()/20000+"分钟");
                        }
                        if (station.getBusId()==1){
                            tvPlatfromtwoDistanceTwo.setText("距离"+station.getDistance()+"m");
                            tvPlatfromtwoTimetwo.setText("剩余时间"+station.getDistance()/20000+"分钟");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {

            }
        });

    }

    Handler mhandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Post();
            mhandler.postDelayed(runnable, 5000);
        }
    };

    private void initView() {
        tvPlatfromoneDistanceOne = (TextView) findViewById(R.id.tv_platfromone_distance_one);
        tvPlatfromoneTimeone = (TextView) findViewById(R.id.tv_platfromone_timeone);
        tvPlatfromoneDistanceTwo = (TextView) findViewById(R.id.tv_platfromone_distance_two);
        tvPlatfromoneTimetwo = (TextView) findViewById(R.id.tv_platfromone_timetwo);
        tvPlatfromtwoDistanceOne = (TextView) findViewById(R.id.tv_platfromtwo_distance_one);
        tvPlatfromtwoTimeone = (TextView) findViewById(R.id.tv_platfromtwo_timeone);
        tvPlatfromtwoDistanceTwo = (TextView) findViewById(R.id.tv_platfromtwo_distance_two);
        tvPlatfromtwoTimetwo = (TextView) findViewById(R.id.tv_platfromtwo_timetwo);
        bt_quiry= (Button) findViewById(R.id.bt_quiry);
        bt_quiry.setOnClickListener(this);

        alertDialog = new AlertDialog.Builder(BusActivity.this)
                .setTitle("网络设置")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent(Settings.ACTION_WIFI_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消",null)
                .setView(LayoutInflater.from(BusActivity.this).inflate(R.layout.wifiset,null))
                .create();
    }

    @Override
    public void onClick(View v) {
        handler.post(runnable);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit(){
        if(!isExit){
            isExit=true;
            handler.sendEmptyMessageDelayed(0,2000);
        }else{
            finish();
        }
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=false;
        }
    };

    LoadingDialog loadingDialog;
    private void showloadingDialog(){
        if (loadingDialog==null){
            loadingDialog=new LoadingDialog(this);
        }
        loadingDialog.setTitle("数据加载中");
        if (!loadingDialog.isShowing())loadingDialog.show();
    }

}
